<?php
declare(strict_types=1);

namespace App\Controller;

use App\Constants\Consts;
use App\Libs\DingDing;
use Hyperf\Contract\ConfigInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\View\RenderInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;

use function Hyperf\Support\env;

/**
 * sitemap管理
 */
class ToolController extends AbstractController
{
    #[Inject(required: true)]
    public ConfigInterface $config;
    #[Inject(lazy: true)]
    public RenderInterface $view;
    // 提交的参数
    protected array $params;

    /**
     * 替换域名视图
     */
    public function replace()
    {
        return $this->view->render('tools/domain_replace', [
            'v' => time(),
            'gno' => env('APP_NAME')
        ]);
    }

    /**
     * 处理域名替换
     */
    public function replaceHandle(RequestInterface $request, ResponseInterface $response): Psr7ResponseInterface
    {
        try {
            $params = $request->all();

            $temp = array_filter(explode("\n", trim($params['domains'])));
            $domains = [];
            foreach ($temp as $item) {
                $arr = explode("	", $item);
                if (empty($arr) || !is_array($arr)) {
                    continue;
                }
                $key = isset($arr[0]) ? trim($arr[0]) : '';
                $val = isset($arr[1]) ? trim($arr[1]) : '';
                if (empty($val)) {
                    return $response->json(['code' => 300, 'message' => '请使用全角空格分割', 'data' => []]);
                }
                $domains[$key] = $val;
            }
            if (empty($domains)) {
                return $response->json(['code' => 300, 'message' => '新域名参数为空', 'data' => []]);
            }

            // 获取现有的旧域名
            $mydomains = file_get_contents(BASE_PATH . Consts::DOMAINS_PATH);
            if (!empty($mydomains)) {
                $mydomains = explode('|', $mydomains);
            } else {
                return $response->json(['code' => 300, 'message' => 'domains.txt不存在或为空', 'data' => []]);
            }

            // 往domain_jump新增数据
            $table = Consts::TABLE_JUMPDOMAIN;
            $str = '';
            foreach ($domains as $oldDomain => $newDomain) {
                if (!in_array($oldDomain, $mydomains)) {
                    return $response->json(['code' => 300, 'message' => $oldDomain . '该域名不在旧域名中', 'data' => []]);
                }
                $str .= "('$oldDomain','$newDomain')" . ",";
            }
            $sql = "INSERT INTO {$table} (`old_domain`,`new_domain`) values" . rtrim($str, ',');
            Db::insert($sql);

            return $response->json(['code' => 200, 'message' => '替换成功', 'data' => []]);
        } catch (\Throwable $e) {
            $msg = 'tool error,msg=' . $e->getMessage() . ',file:' . $e->getFile() . ',line:' . $e->getLine();
            logger()->error($msg);
            DingDing::sendErrorMsg($msg);
            return $response->raw($msg);
        }
    }
}
